package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.RedisConstants;
import com.heima.common.constants.WemediaConstants;
import com.heima.common.constants.WmNewsConstants;
import com.heima.model.common.dtos.PageRequestDto;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmChannelDto;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.wemedia.mapper.WmChannelMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.service.WmChannelService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

/**
 * @Description TODO
 * @Author bo.li
 * @Date 2023/3/16 10:51
 * @Version 1.0
 */
@Service
public class WmChannelServiceImpl extends ServiceImpl<WmChannelMapper, WmChannel> implements WmChannelService {

    @Autowired
    private WmChannelMapper wmChannelMapper;

    @Autowired
    private WmNewsMapper newsMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 查询所有频道
     *
     * @param dto
     * @param
     * @param
     * @return
     */
    @Override
    public ResponseResult findAll(WmChannelDto dto) {
        dto.checkParam();

        LambdaQueryWrapper<WmChannel> queryWrapper = new LambdaQueryWrapper<>();

        //按照创建时间倒序查询
        queryWrapper.orderByDesc(WmChannel::getCreatedTime);
        //按照频道名称模糊查询,名称不能为空
        if (!StringUtils.isEmpty(dto.getName())) {
            queryWrapper.like(WmChannel::getName, dto.getName());
        }
        //按照状态进行精确查找
        if (dto.getStatus() != null){
            queryWrapper.eq(WmChannel::getStatus, dto.getStatus());
        }

        wmChannelMapper.selectList(queryWrapper);
        //分页查询
        Page<WmChannel> page = new Page<>(dto.getPage(), dto.getSize());
        page = this.page(page, queryWrapper);
        PageResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
        result.setData(page.getRecords());
        return result;
    }

    @Override
    public ResponseResult add(WmChannelDto dto) {

        dto.checkParam();
        WmChannel wmChannel = new WmChannel();
        BeanUtils.copyProperties(dto, wmChannel);
        //频道名称不能重复
       LambdaQueryWrapper<WmChannel> queryWrapper = new LambdaQueryWrapper<>();
       queryWrapper.eq(WmChannel::getName, wmChannel.getName());
       if (wmChannelMapper.selectOne(queryWrapper) != null) {
           return ResponseResult.errorResult(AppHttpCodeEnum.CHANNEL_EXIST);
       }
        wmChannel.setCreatedTime(new Date());
        wmChannel.setIsDefault(WemediaConstants.Channel_TYPE_MEDIA);
        wmChannel.setStatus(WemediaConstants.Channel_TYPE_MEDIA);
        wmChannelMapper.insert(wmChannel);
        updateCache();
        return ResponseResult.okResult(wmChannel);
    }

    private void updateCache() {
        redisTemplate.delete(WmNewsConstants.CHANNEL_KEY);
        List<WmChannel> channels = wmChannelMapper.selectList(null);
        redisTemplate.opsForValue().set(WmNewsConstants.CHANNEL_KEY, channels);
    }

    @Override
    public ResponseResult revise(WmChannelDto dto) {
        dto.checkParam();

        WmChannel wmChannel = new WmChannel();
        BeanUtils.copyProperties(dto, wmChannel);
        //如果频道被引用则不能禁用
        LambdaQueryWrapper<WmNews> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WmNews::getChannelId, dto.getId());
        //查询该频道是否被引用
        List<WmNews> wmNews = newsMapper.selectList(wrapper);
        if (!CollectionUtils.isEmpty(wmNews)){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE, "该频道被引用，不能禁用");
        }
        wmChannel.setDescription(dto.getDescription());
        wmChannel.setId(dto.getId());
        wmChannel.setIsDefault(WemediaConstants.Channel_TYPE_MEDIA);
        wmChannel.setName(dto.getName());
        wmChannel.setOrd(dto.getOrd());
        wmChannel.setStatus(dto.getStatus()? 1 : 0);
        wmChannelMapper.updateById(wmChannel);

        //更新缓存
        updateCache();
        return ResponseResult.okResult(wmChannel);
    }

    @Override
    public ResponseResult remove(Integer id) {
        WmChannel wmChannel = wmChannelMapper.selectById(id);
        //只有禁用的频道才能删除
        if (wmChannel.getStatus().equals(WemediaConstants.Channel_TYPE_MEDIA)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE, "该频道已启用，不能删除");
        } else if (wmChannel.getStatus().equals(WemediaConstants.Channel_TYPE_USER)) {
            wmChannelMapper.deleteById(id);
        }
        updateCache();
        return ResponseResult.okResult(wmChannel);
    }
}